<!-- 角色编辑弹窗 -->
<template>
  <div>
    <ele-modal width="80%"
               height="500px"
               title="推广员列表"
               :visible="drawerEditBoolen"
               @close="closeFn"
               :maxable="true">
      <!-- <el-drawer :visible="drawerEditBoolen"
               size="50%"
               :before-close="handleClose"
               ref="drawer"> -->
      <role-search @search="reload" />
      <el-card shadow="never">
        <div class="flex-column-between ">
          <ele-pro-table ref="table"
                         :columns="columns"
                         :datasource="datasource"
                         cache-key="systemUserTable">
            <!-- 表头工具栏 -->
            <template v-slot:toolbar> </template>
            <!-- 用户名列 -->
            <!-- 状态列 -->
            <template v-slot:status="{ row }">
              <el-switch :active-value="1"
                         :inactive-value="0"
                         v-model="row.status"
                         @change="editStatus(row)" />
            </template>

            <template v-slot:amount="{ row }">
              <div style="color: #1890ff"
                   v-if="row.amount_direction == 1">
                +{{ row.amount }}
              </div>
              <div style="color: red"
                   v-if="row.amount_direction == 2">
                -{{ row.amount }}
              </div>
            </template>
            <template v-slot:nickname="{ row }">
              <div v-if="row.nickname">
                <div class="realNameStyle">
                  <img class="avaterName"
                       :src="row.avatar"
                       alt="" />
                  <span>{{ row.nickname }}</span>
                </div>
              </div>
              <div v-else>-----</div>
            </template>
            <template v-slot:operation_source="{ row }">
              <div>
                {{ operation_source(row.operation_source) }}
              </div>
            </template>
            <template v-slot:amount_type="{ row }">
              <div>
                {{ row.amount_type==1?'余额变动':'收益变动' }}
              </div>
            </template>
            <template v-slot:action="{ row }">

              <el-link type="primary"
                       :underline="false"
                       icon="el-icon-edit"
                       @click="openAdd(row)">
                编辑
              </el-link>
              <el-link type="success"
                       :underline="false"
                       icon="el-icon-view"
                       @click="openDetail(row)">
                详情
              </el-link>
              <el-link :type="row.state==1?'danger':' primary'"
                       :underline="false"
                       icon="el-icon-warning-outline"
                       @click="blockFn(row)">
                {{row.state==2?'解禁':'禁用' }}
              </el-link>

            </template>

          </ele-pro-table>

          <!-- <div class="drawer__footer">
            <el-button round
                       type="plain"
                       @click="handleClose()"
                       size="medium">返回</el-button>
          </div> -->
        </div>
      </el-card>

    </ele-modal>
    <!-- </el-drawer> -->
    <!-- 图片预览 -->
    <RoleEditAdd :data="currentAdd"
                 :isEdit="true"
                 :drawerEditBoolen.sync="drawerEditBoolenAdd"
                 @done="reload" />
    <el-image-viewer v-if="viewerVisible"
                     style="z-index: 9999"
                     :on-close="closeViewer"
                     :url-list="imgViewArr" />
    <promotersDetails :data="currentDetail"
                      :drawerEditBoolen.sync="drawerEditBoolenDetail"
                      @done="reload" />
  </div>
</template>

<script>
import RoleSearch from './role-searchPromoters';
import RoleEditAdd from './role-editAdd';
import promotersDetails from './promotersDetails'
import ElImageViewer from 'element-ui/packages/image/src/image-viewer';
import { distributorEditState } from '@/api/userList/index'
import { promoterGetList } from '@/api/partnerApi/index'
import { promoterAdd, promoterEdit, editState } from '@/api/partnerApi/index'
// import {
//   userOssSignature,
//   qnyOssSignature
// } from '@/api/creatCenter/material';
// import { storageConfigDetail } from '@/api/storageInfo/index';

// import axios from 'axios';
// import {
//   siteCategoriesInsert,
//   siteCategoriesList,
//   siteCategoriesModify,
//   siteCategoriesDetail
// } from '@/api/serviceManagement/categoriesList';
import { upload } from '@/api/saveImg/index'
import { editClassify, addClassify } from '@/api/classifyList/index'
export default {
  name: 'pictureEdit',
  components: { ElImageViewer, RoleEditAdd, promotersDetails, RoleSearch },
  props: {
    drawerEditBoolen: {
      type: Boolean,
      default: false
    },
    // 修改回显的数据
    data: Object
  },
  data () {
    // const categoryImage = (rule, value, callback) => {
    //   console.log(this.form.img);
    //   if (!this.form.img) {
    //     callback(new Error('请上传图片'));
    //   } else {
    //     callback();
    //   }
    // };
    const DEFAULT_FORM = {
      daziPercent: '',
      servicePercent: '',
      communityPercent: '',
      state: 2,
    };
    return {
      currentAdd: null,
      drawerEditBoolenAdd: false,
      currentDetail: null,
      drawerEditBoolenDetail: false,


      storageMode: 2,
      options: [],
      imageUrl: '',
      imgViewArr: [],
      viewerVisible: false,
      // 表单数据
      form: { ...DEFAULT_FORM },
      dialogImageUrl: '',
      fileList: [],
      dialogVisible: false,
      // 表单验证规则
      rules: {
        daziPercent: [
          {
            required: true,
            message: '请填写搭子比例',
            trigger: 'blur'
          }
        ],


        servicePercent: [
          {
            required: true,
            message: '请填写服务比例',
            trigger: 'blur'
          }
        ],
        communityPercent: [
          {
            required: true,
            message: '请填写社群比例',
            trigger: 'blur'
          }
        ],
        // // 站点 图片上传
        // img: [
        //   { required: true, validator: categoryImage, trigger: 'change' }
        // ]
      },
      // 提交状态
      loading: false,
      // 是否是修改
      isUpdate: false,
      showChoose: false,
      columns: [
        {
          columnKey: 'index',
          type: 'index',
          width: 45,
          align: 'center',
          showOverflowTooltip: true,
          fixed: 'left'
        },
        {
          prop: 'name',
          label: '昵称',
          align: 'center',
          showOverflowTooltip: false,
          minWidth: 110,

        },
        {
          prop: 'account',
          label: '账号',
          align: 'center',
          sortable: 'custom',
          showOverflowTooltip: true,
          minWidth: 110,

        },
        {
          prop: 'totayUser',
          label: '用户总数',
          sortable: 'custom',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 110,

        },

        {
          prop: 'todayAddUserNum',
          label: '今日新增用户',
          align: 'center',
          sortable: 'custom',
          showOverflowTooltip: true,
          minWidth: 110,

        },
        {
          prop: 'totayIncome',
          label: '累计收益',
          align: 'center',
          sortable: 'custom',
          showOverflowTooltip: true,
          minWidth: 110,

        },
        {
          prop: 'todayIncome',
          label: '今日收益',
          align: 'center',
          sortable: 'custom',
          showOverflowTooltip: true,
          minWidth: 110,

        },

        {
          prop: 'create_time',
          label: '创建时间',
          sortable: 'custom',
          showOverflowTooltip: false,
          minWidth: 110,
          formatter: (_row, _column, cellValue) => {
            return this.$util.toDateString(cellValue);
          }
        },
        {
          columnKey: 'action',
          label: '操作',
          minWidth: 150,
          align: 'center',
          resizable: false,
          slot: 'action',
          showOverflowTooltip: false,
          fixed: 'right'
        },
      ]
    };
  },
  activated () {

  },
  methods: {
    async blockFn (row) {
      const res = await editState({
        id: row.id,

        state: row.state == 1 ? 2 : 1
      })
      if (res.code == 0) {
        this.reload()

      }
    },
    openDetail (row) {
      if (row?.id) {
        // const res = await siteCategoriesDetail(row.id);

        this.currentDetail = row;
        // 用户余额管理
        this.drawerEditBoolenDetail = !this.drawerEditBoolenDetail;
      } else {
        this.drawerEditBoolenDetail = !this.drawerEditBoolenDetail;
        this.currentDetail = null;
      }
    },
    async openAdd (row) {
      console.log(row);
      if (row?.id) {
        // const res = await siteCategoriesDetail(row.id);

        this.currentAdd = row;
        // 用户余额管理
        this.drawerEditBoolenAdd = !this.drawerEditBoolenAdd;
      } else {
        this.drawerEditBoolenAdd = !this.drawerEditBoolenAdd;
        this.currentAdd = null;
      }
    },
    datasource ({ page, limit, where }) {
      return promoterGetList({ pid: this.form.pid, page, limit, ...where });
    },
    /* 刷新表格 */
    reload (where) {
      this.$refs.table.reload({ page: 1, where: where });
    },
    inputChangeWx (e, value, val) {



      if (Number(value) > 100) {
        this.$message({
          message: '输入的折扣大于100请重新输入',
          type: 'warning'
        });
        if (val == 'daZiRatio') {
          this.form.daZiRatio = 100;
        } else if (val == 'fuWuRatio') {
          this.form.fuWuRatio = 100;
        } else {
          this.form.sheQunRatio = 100;
        }

        return false;
      }

    },
    // 获取存储配置
    // async storageConfig () {
    //   const res = await storageConfigDetail();

    //   // console.log(res.storageMode);

    //   this.storageMode = res?.storageMode;
    // },
    // 关闭查看器
    closeViewer () {
      this.viewerVisible = false;
    },
    // 下载图片
    handleDownload (file) {
      window.open(file.url);
    },
    // 删除图片
    handleRemove () {
      this.fileList = [];
      this.imageUrl = '';
      this.form.img = this.imageUrl;
    },
    //  图片上传个数超过限制
    exceedFn () {
      this.$message({
        message: '图片上传已达到上限,请删除后再上传',
        type: 'warning'
      });
    },
    handlePictureCardPreview () {
      const imgStr = this.imageUrl;
      console.log(imgStr);
      if (imgStr.length) {
        if (imgStr.includes(',')) {
          console.log('字符串中包含逗号');
          // 包含的进行slice(',') 分割

          this.imgViewArr = imgStr.split(',').map((item) => item.trim());
        } else {
          console.log('字符串中不包含逗号');
          this.imgViewArr = imgStr.split();
        }

        this.viewerVisible = true;
      } else {
        this.$message({
          message: '没有上传图片无法进行预览',
          type: 'warning'
        });
      }
    },

    // 关闭抽屉
    closeFn () {
      console.log('查看详情');
      this.$emit('update:drawerEditBoolen', false);
    },
    async handleFileChange (file) {

      this.aliFn(file)
    },
    // 阿里云
    async aliFn (file) {
      this.loading = true;

      let files = file.raw;

      console.log(files)
      // 构建请求参数
      let params = new FormData();
      console.log(params);

      //   params.append('signature', '132321313');
      params.append('file', files);
      console.log(params);

      //   let config = {
      //     headers: {
      //       'Access-Control-Allow-Origin': '*',
      //       'x-oss-callback-Authorization': getToken()
      //     }
      //   };

      const res = await upload(params);
      //   let result = await axios.post(res.host, param, config);
      //   let url = res.host + '/' + date + suffix;
      console.log(res);
      if (res.code == 0) {
        this.form.img = res.data.url
        this.loading = false;
      }
      //   this.form.categoryImages = url;
      //   this.imageUrl = url;
      //   this.loading = false;
    },

    /* 保存编辑 */
    save () {
      this.$refs['form'].validate((valid) => {
        if (!valid) {
          return false;
        }
        // if (this.isUpdate) {
        //   this.form.img = this.imageUrl;
        // }
        const data = {
          ...this.form
        };
        console.log(data);
        this.loading = true;

        const saveOrUpdate = distributorEditState
        saveOrUpdate(data)
          .then((msg) => {
            console.log(msg);
            this.loading = false;
            this.$message.success(msg.message);

            this.handleClose();
            this.$emit('done');
          })
          .catch((e) => {
            this.loading = false;
            this.$message.error(e.message);
          });
      });
    }
    /* 更新visible */
  },
  watch: {
    drawerEditBoolen (visible) {
      this.$nextTick(() => {
        if (visible) {
          console.log(this.data);
          if (this.data) {
            this.form.pid = this.data.id;
            this.reload()
            // this.$util.assignObject(this.form, {
            //   ...this.data
            // });
            // this.form.daziPercent = this.data.dazi_percent
            // this.form.servicePercent = this.data.service_percent
            // this.form.communityPercent = this.data.community_percent
            this.isUpdate = true;
          } else {
            this.isUpdate = false;
          }
        } else {
          this.$nextTick(() => {
            this.$refs['form'].resetFields();
            console.log(this.form);
          });
          this.fileList = [];

        }
      });
    }
  }
};
</script>

<style lang="less" scoped>
/*隐藏input（type=number)右边的小箭头*/
/deep/.delInput input::-webkit-outer-spin-button,
/deep/.delInput input::-webkit-inner-spin-button {
  -webkit-appearance: none !important;
}
/deep/.delInput input[type='number'] {
  -moz-appearance: textfield;
}
.foodsDiv div {
  margin-left: 20px;
  margin-top: 10px;
}
.height83 {
  height: 83vh;
}
.hLabel {
  margin: 10px 0 20px;
  font-weight: 700;
  &::before {
    content: '';
    display: inline-block;
    vertical-align: top;

    margin-right: 5px;
    height: 23px;
    width: 6px;
    background-color: #1e6ceb;
  }
}
.drawer__footer {
  display: flex;
  justify-content: flex-start;
  margin-left: 15px;
}
</style>
